<template>
	<view>
		<view class="topLayout" :class="{ 'fixed': isTopFixed }" @click="toLogin()">
			<image src="../../static/home.png" style="width: 40rpx; height: 40rpx; margin-left: 20rpx;"></image>
			<view style="margin-left: 20rpx;">二师兄傻大串</view>
		</view>
		<view class="content">
			<!-- 左侧滚动 -->
			<scroll-view class="menu-wrapper" scroll-y :scroll-top="left_scroll" scroll-with-animation="true">
				<view class="left-content">
					<view style="position: relative;" v-for="(item,index) in shopList" :key="index" ref="menuList"
						@click="select(index)" :class="{'current': currentIndex == index}">
						<view class="menu-item">{{item.categoryName}}</view>
						<!-- <text class="allcount" v-if="getAllCount>=item.count&&item.count>0">{{item.count}}</text> -->
						<text class="allcount" v-if="item.count>0">{{item.count}}</text>
					</view>
				</view>
			</scroll-view>
			<!-- 右侧滚动 -->
			<scroll-view class="foods-wrapper" scroll-y :style="'height:'+windows_height+'px'" :scroll-top="foodSTop"
				@scroll="myscroll" scroll-with-animation="true">
				<view ref="foodsWrapper">
					<view ref="foodList" class="foods" v-for="(item, i) in shopList" :key="i">
						<view class="food-title" style="background: #f3f5f7">
							{{item.categoryName}}
						</view>
						<view class="food" v-for="(food, index) in item.shopInfoVOList" :key="index"
							@click="showShop(food.shopId)">
							<image :src="$getPicture(food.shopUrl)" style="width: 75px;height: 75px;margin-top: 6px;">
							</image>
							<view class="food-info">
								<text style="font-size: 15px;margin-top: 2px;">{{food.shopName}}</text>
								<text style="font-size: 13px;margin: 2px 0;">{{food.shopIntroduce}}</text>
								<text style="font-size: 13px;margin: 2px 0 4px;">月售{{food.shopSales}}</text>
								<!-- 规格样式 -->
								<view class="food-btm">
									<view class="food-price">￥{{food.shopAmount}}</view>
									<!-- 选规格 -->
									<view v-if="food.shopSpecificationVOList.length > 0"
										style="width: 200rpx; display: flex; justify-content: end;"
										@tap.stop="selectSpecification(food)">
										<view style="width: 40rpx;"/>
										<view class="cartStyle">
											<view v-if="food.count" class="skuCount">{{food.count}}</view>
											<view>选规格</view>
										</view>
									</view>
									<!-- 商品起购 -->
									<view v-else-if="food.minimumQuantity>0 && food.shopSpecificationVOList.length==0 && item.count==0" 
									style="width: 200rpx; display: flex; justify-content: end;"
									@tap.stop="batchToCart(food)">
										<view style="width: 40rpx;"/>
										<view class="cartStyle">
											<view>{{food.minimumQuantity}}份起购</view>
										</view>
									</view>
									<!-- 商品加减 -->
									<view v-else style="width: 200rpx; display: flex; justify-content: end;">
										<view style="display: flex;" v-if="food.count>0">
											<image src="../../static/des.png" class="food-count"
												@tap.stop="decreaseCart(food)"></image>
											<view style="align-items: center; margin: 0 5rpx;">{{food.count}}</view>
										</view>
										<image src="../../static/add2.png" class="food-count" @tap.stop="addCart(food)">
										</image>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<!-- 购物车信息 -->
			<view class="cartLists" v-show="showCart">
				<scroll-view scroll-y style="max-height: 400px;">
					<view class="titles">
						<view>已选商品</view>
						<view class="clear" @click="delAll()">
							清空购物车
						</view>
					</view>
					<view class="lists">
						<view class="list-texts" v-for="(item,index) in cartShopList">
							<view style="display: flex; width: 100%;">
								<image :src="$getPicture(item.shopPic)"
									style="width: 75px;height: 75px;margin-top: 6px; border-radius: 8rpx;">
									<view
										style="flex: 1; margin: 6px 0 0 6px; display: flex; flex-direction:column;justify-content: center;">
										<view style="display: flex; flex: 1; align-items: center;">{{item.shopName}}
										</view>
										<view v-if="item.flavourName" style="font-size: 24rpx; color: #8799a3;">({{item.flavourName}})</view>
										<view style="display: flex; flex: 1; align-items: center;">
											<view style="width: 100px;">￥{{item.saleAmount}}</view>
											<view
												style="flex: 1; display: flex; justify-content: end; margin-right: 20rpx;">
												<view style="display: flex;" v-show="item.shopNum>0">
													<image src="../../static/des.png" class="food-count"
														@click="decreaseCart(item)"></image>
													<view style="margin: 0 5rpx;">{{item.shopNum}}</view>
												</view>
												<image src="../../static/add2.png" class="food-count"
													@click="addCart(item)">
											</view>
										</view>
									</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<!-- 商品详情与多规格购买 -->
			<specification v-if="style" :shopinfo="shopinfo" :tableNum="tableNum" :quantityShow="quantityShow" @closeSpecification="closeSpecification"></specification>
			<!-- 遮罩层 -->
			<view class="listMask" v-show="showCart || style" @click="toggleList()"></view>
		</view>
		<view style="height: 60px;"></view>
		<view class="cart">
			<view style="flex: 1;display: flex; " @click="openPoup()">
				<view class="leftPic">
					<view v-if="allSaleCount>0" class="cartCount">{{allSaleCount}}</view>
					<image src="../../static/cartList.png" style="height: 80rpx; width: 80rpx;"></image>
				</view>
				<view v-if="allSaleAmount>0" style="flex: 1;display: flex; align-items: center;padding-left: 30rpx;">
					￥{{allSaleAmount}}</view>
				<view v-else style="flex: 1;display: flex; align-items: center;padding-left: 30rpx;">未选择商品</view>
			</view>
			<view class="toPay" @click="submit()">确认订单</view>
		</view>
	</view>

</template>

<script>
	import common from '../../common/common.js'
	import Vue from 'vue'
	import decimal from 'decimal.js'
	import socket from '../../common/webSocket.js'
	import specification from '../../components/specification.vue'

	export default {
		data() {
			return {
				title: 'Hello',
				shopList: [], //分类和商品数据
				windows_height: 0, //屏幕高度
				foodSTop: 0, //右侧的滑动值
				currentIndex: 0,
				last: 0,
				right_height: [], //右侧每个内容的高度集合
				select_index: 0,
				left_height: 0, //左侧总高度
				left_scroll: 0, //左侧滑动值
				cartShopList: [], //购物车列表数据
				allSaleAmount: 0, //购物车总价格
				allSaleCount: 0, //购物车总数量
				tableNum: 0, //餐桌号
				dinerNum: 0, //用餐人数
				timeout: null,
				showCart: false, //购物车弹出层
				style: false, //选择规格弹出层
				shopinfo: [] ,//传给规格页面的数据
				quantityShow :false,//规格页面判断起购数量
			}

		},
		components: {
			specification
		},
		onLoad(option) {
			this.dinerNum = option.dinerNum;
			this.tableNum = option.tableNum;
			socket.init();
			socket.setMethod(this.cartCount, this.clearCart, this.toOrderList);
			this.getCartAndList()
			this.getAllSaleAmount();
			this.getAllCartCount();
			this.windows_height = Number(uni.getSystemInfoSync().windowHeight) - 55;
			if (option.openCart == 1) {
				this.openPoup();
			}
			setTimeout(() => {
				this.getHeightList();
			}, 1000)
		},
		computed: {
			getList() {
				let result = [];
				this.shopList.forEach((good) => {
					good.shopInfoVOList.forEach((food) => {
						if (food.count) {
							result.push(food)
						}
					})
				})
				return result
			},
			// 加入购物车后分类数据的变化量
			getAllCount: function(item) {
				let result = [];
				let count = 0;
				for (let i = 0; i < this.shopList.length; i++) {
					count = 0;
					this.shopList[i].shopInfoVOList.forEach((food) => {
						if (food.count >= 0) {
							count += food.count
							Vue.set(this.shopList[i], 'count', count)
						}
					})
					result.push(count)
				}

				result.sort(function(a, b) {
					return a - b;
				})
				count = result[result.length - 1]
				return count;
			},
		},
		methods: {
			//获取分类和商品数据
			getAllList() {
				return new Promise((resolve, reject) => {
					common.get({
						url: '/orderEat/orderEat/wxShopList',
						success: (res) => {
							this.shopList = res.data;
							let count = 0;
							for (var i = 0; i < this.shopList.length; i++) {
								count = this.shopList[i].count;
								Vue.set(this.shopList[i], 'count', count);
								this.shopList[i].shopInfoVOList.forEach((food) => {
									Vue.set(food, 'count', food.shopNum)
								})
							}
							resolve();
						},
						fail: (err) => {
							reject(err);
						}
					})
				})

			},
			//显示已选择的购物车数据和商品列表数据
			async getCartAndList() {
				await this.getAllList();
				common.get({
					url: '/orderEat/shopInfo/cartList/' + this.tableNum,
					success: (res) => {
						this.cartShopList = res.data;
						this.shopList.forEach((category) => {
							category.shopInfoVOList.forEach((shop) => {
								this.cartShopList.forEach((cart) => {
									if (cart.shopId == shop.shopId) {
										if (shop.count != null) {
											shop.count += cart.shopNum;
										} else {
											Vue.set(shop, 'count', cart.shopNum);
										}

									}
								})
							})
						})
					}
				});
			},

			// 点击侧边栏
			select(index) {
				this.currentIndex = index;
				this.setScrollH(index);
			},
			//查看商品详情
			showShop(parm) {
				uni.navigateTo({
					url: "/pages/shop/shopDetail?shopId=" + parm + "&tableId=" + this.tableNum
				})
				//this.shopDetail = true;
			},
			// 设置点击侧边栏右边滚动的高度
			setScrollH: function(index) {
				var that = this;
				let height = 0;
				var query = uni.createSelectorQuery();
				let foods = query.selectAll('.foods');
				this.$nextTick(function() {
					foods.fields({
						size: true
					}, data => {
						if (index == 0) {
							that.foodSTop = 0;
						}
						for (let i = 0; i < index; i++) {
							height += parseInt(data[i].height);
							// console.log('fh', foods);
							that.foodSTop = height;
							// console.log(that.foodSTop)
						}
					}).exec();
				})
			},
			//购物车数据处理
			cartCount(data) {
				if (data.tableId == this.tableNum) {
					this.shopList.forEach((category) => {
						category.shopInfoVOList.forEach((shop) => {
							if (data.shopId == shop.shopId) {
								if (shop.count != null && data.decreaseItem == 0) {
									shop.count += data.shopNum;
								} else {
									Vue.set(shop, 'count', data.shopNum);
								}
							}
						})
					})
					this.getAllSaleAmount();
					this.getAllCartCount();
					common.get({
						url: '/orderEat/shopInfo/cartList/' + this.tableNum,
						success: (res) => {
							this.cartShopList = res.data;
						}
					})
				}
			},
			//清空购物车数据后续处理
			clearCart() {
				this.getCartAndList();
				this.getAllSaleAmount();
				this.getAllCartCount();
				common.get({
					url: '/orderEat/shopInfo/cartList/' + this.tableNum,
					success: (res) => {
						this.cartShopList = res.data;
					}
				})
			},
			//提交订单后的跳转
			toOrderList() {
				uni.showToast({
					title: '订单已提交',
					complete: () => {
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/order/orderList?tableId=' + this.tableNum
							});
						}, 1500); // 延迟1秒后跳转
					}
				});
			},
			//购物车添加
			addCart(parm) {
				// if (parm.count > 0) {
				// 	parm.count++;
				// } else {
				// 	Vue.set(parm, 'count', 1);
				// };
				common.post({
					url: '/orderEat/shopInfo/addCartShop',
					formData: {
						shopId: parm.shopId,
						shopName: parm.shopName,
						shopPic: parm.shopUrl,
						shopNum: 1,
						shopAmount: parm.shopAmount,
						tableId: this.tableNum
					},
					success: (res) => {
						//this.allSaleCount++;
						//this.allSaleAmount = new decimal(this.allSaleAmount).add(parm.shopAmount);
					}
				})
			},
			//起购数量批量加入购物车
			batchToCart(param){
				common.post({
					url: '/orderEat/shopInfo/addCartShopBatch',
					formData: {
						shopId: param.shopId,
						shopName: param.shopName,
						shopPic: param.shopUrl,
						shopAmount: param.shopAmount,
						shopNum: param.minimumQuantity,
						tableId: this.tableNum
					},
					success: (res) => {
						
					}
				})
			},
			//购物车减少
			decreaseCart(param) {
				// parm.count--;
				common.post({
					url: '/orderEat/shopInfo/delCartShop',
					formData: {
						cartId: param.cartId,
						shopId: param.shopId,
						shopName: param.shopName,
						shopNum: param.count,
						shopAmount: param.shopAmount,
						tableId: this.tableNum
					},
					success: (res) => {
						// this.allSaleCount--;
						// this.allSaleAmount = new decimal(this.allSaleAmount).sub(parm.shopAmount);
					}
				})
			},
			// 清空购物车
			delAll() {
				common.post({
					url: '/orderEat/shopInfo/delAllCartShop/' + this.tableNum,
					formData: {
						shopCarts: this.cartShopList
					},
					success: (res) => {}
				})
			},
			//显示购物车列表
			openPoup() {
				this.showCart = true;
				common.get({
					url: '/orderEat/shopInfo/cartList/' + this.tableNum,
					success: (res) => {
						this.cartShopList = res.data;
					}
				})
			},

			//显示购物车总价格
			getAllCartCount() {
				common.get({
					url: '/orderEat/shopInfo/cartNumCount/' + this.tableNum,
					success: (res) => {
						this.allSaleCount = res.msg;
					}
				})
			},
			//显示购物车总数量
			getAllSaleAmount() {
				common.get({
					url: '/orderEat/shopInfo/cartAmount/' + this.tableNum,
					success: (res) => {
						this.allSaleAmount = res.msg;
					}
				})
			},
			//选择规格
			selectSpecification(param) {
				this.style = true;
				this.shopinfo = param;
				if(param.minimumQuantity>0){
					this.quantityShow = true
				}else{
					this.quantityShow = false
				}
			},
			//关闭遮罩层
			toggleList() {
				if (this.showCart == true) {
					this.showCart = false;
				};
				if (this.style == true) {
					this.style = false;
				}
			},
			//关闭选择规格组件
			closeSpecification(param){
				this.style = param;
			},
			
			getHeightList() {
				let _this = this;
				let selectorQuery = uni.createSelectorQuery().in(this);
				selectorQuery.select('.left-content').boundingClientRect(function(rects) {
					_this.left_height = rects.height;
				});
				selectorQuery.selectAll('.foods').boundingClientRect(function(rects) {
					_this.right_height = rects.map((item) => item.top);
				}).exec();
			},
			//提交订单
			async submit() {
				await this.loadCartList();
				common.post({
					url: "/orderEat/orderInfo/add",
					formData: {
						shopCartList: this.cartShopList,
						tableId: this.tableNum,
						dinerNum: this.dinerNum
					},
					success: (res) => {}
				})
			},
			//返回首页
			toLogin() {
				uni.switchTab({
					url: "/pages/login/login"
				})
			},

			//加载购物车信息
			loadCartList() {
				return new Promise((resolve, reject) => {
					common.get({
						url: '/orderEat/shopInfo/cartList/' + this.tableNum,
						success: (res) => {
							this.cartShopList = res.data;
							resolve();
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			myscroll(e) {
				//引入节流	
				let right_content_height = e.detail.scrollHeight - this.windows_height;
				if (right_content_height == e.detail.scrollTop) {
					return;
				}
				let scroll_top = e.detail.scrollTop + 110; //110是banner图的高度
				//判断当前的scrollTop在哪个区间内;
				let now = +new Date();
				if (now - this.last > 100) {
					this.last = now;
					let active_index = this.right_height.findIndex((value, index, arr) => value <= scroll_top &&
						scroll_top < arr[index + 1]);
					this.currentIndex = active_index;
					if (this.left_height - this.windows_height) {
						//如果有超出部分
						let diff = this.left_height - this.windows_height
						this.left_scroll = Math.round((active_index * diff) / (this.shopList.length - 1))
					}
				}
			}
		}
	}
</script>

<style>
	.topLayout {
		width: 100%;
		height: 140rpx;
		display: flex;
		align-items: center;
		padding-top: 30rpx;
		position: sticky;
		top: 0;
		background-color: #fff;
		z-index: 1;
	}

	.content {
		display: flex;
		width: 100%;
		/* position: absolute;
		top: 0;
		bottom: 55px;
		overflow: hidden; */
	}

	.current {
		position: relative;
		z-index: 0;
		background-color: #fff;
		color: #00A0DC;
		border-left: 5px solid #00A0DC;
	}

	.menu-wrapper {
		text-align: center;
		width: 22%;
		display: flex;
		flex-direction: column;
		background: #f3f5f7;

	}

	.menu-item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50px;
	}

	.allcount {
		position: absolute;
		right: 6px;
		top: 8px;
		display: inline-block;
		padding: 0 4px;
		font-size: 9px;
		line-height: 16px;
		font-weight: 400;
		border-radius: 50%;
		background-color: #f01414;
		color: #ffffff;
	}

	.foods-wrapper {
		margin-left: 4px;
		width: 78%;
	}

	.food {
		height: 100px;
		display: flex;
	}

	,
	.food-btm {
		display: flex;
		height: 40rpx;
	}

	,
	.content {
		display: flex;
		flex-direction: row;
	}

	.food-title {
		padding: 2px 0;
		font-size: 26rpx;
	}

	.food-info {
		margin-left: 10px;
		margin-right: 16px;
		display: flex;
		flex-direction: column;
		flex: 2;
	}

	.food-price {
		color: #f01414;
		flex: 1;
		font-size: 16px;
	}

	.food-count {
		width: 20px;
		height: 20px;
		color: #CCCCCC;
	}

	.cart {
		position: fixed;
		bottom: -1px;
		left: 0;
		right: 0;
		height: 54px;
		z-index: 99;
		display: flex;
		background-color: gainsboro;
	}

	.toPay {
		width: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: bisque;
		color: #fff;
	}

	.leftPic {
		width: 100rpx;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		border-radius: 100rpx;
		position: relative;
		top: -10rpx;
	}

	.cartLists {
		position: fixed;
		bottom: 54px;
		left: 0;
		right: 0;
		z-index: 90;
	}

	.titles {
		display: flex;
		background: #F3F5F7;
		justify-content: space-between;
		padding: 4px 8px;
	}

	.lists {
		background: #F8F8F8;
		padding-bottom: 10px;
	}

	.list-texts {
		display: flex;
		flex-direction: row;
	}

	.cartCount {
		position: absolute;
		right: -6px;
		top: 0;
		display: inline-block;
		padding: 0 6px;
		font-size: 9px;
		line-height: 16px;
		font-weight: 400;
		border-radius: 10px;
		background-color: #f01414;
		color: #ffffff;
	}

	.cartStyle {
		background-color: royalblue;
		border-radius: 12rpx;
		font-size: 28rpx;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 20rpx;
		position: relative;
	}
	
	.skuCount {
		position: absolute;
		right: -10px;
		top: -10rpx;
		display: inline-block;
		padding: 0 6px;
		font-size: 9px;
		line-height: 16px;
		font-weight: 400;
		border-radius: 10px;
		background-color: #f01414;
		color: #ffffff;
	}

	/* 遮罩层 */
	.listMask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 89;
		opacity: 0.5;
		background: #6a7076;
	}
</style>